from flask import current_app, redirect, url_for, session, g
from . import admin_blue
from flask import request, render_template, abort, jsonify
from first_info.models import User, News, Category
from first_info.utils.comment import user_login_data
import time, datetime
from first_info import constants, response_code, db
from first_info.utils.file_storage import upload_file


# 新闻分类管理
@admin_blue.route('/news_type', methods=['GET', 'POST'])
def news_type():
    if request.method == 'GET':
        # 查询新闻分类的数据库
        categories = []
        try:
            categories = Category.query.filter(Category.id != 1).all()
        except Exception as e:
            current_app.logger.error(e)

        data = {
            'categories': categories
        }
        return render_template('admin/news_type.html', **data)

    if request.method == 'POST':
        # 1.接收参数
        cname = request.json.get('name')
        cid = request.json.get('id')
        # 2.校验参数
        if not cname:
            return jsonify(errno=response_code.RET.PARAMERR, errmag='缺少参数')
        # 3.查询数据库，有传id就是修改，没有传id就是增加
        if cid:
            try:
                category = Category.query.get(cid)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=response_code.RET.DBERR, errmag='未查询到信息')
            if not category:
                return jsonify(errno=response_code.RET.DATAERR, errmag='分类不存在')
            category.name = cname
        else:
            category = Category()
            category.name = cname
            db.session.add(category)
        # 4.同步到数据库
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DBERR, errmag='修改失败')
        return jsonify(errno=response_code.RET.OK, errmag='成功')









# 新闻版式编辑详情
@admin_blue.route('/news_edit_detail/<int:news_id>', methods=['GET', 'POST'])
def news_edit_detail(news_id):
    if request.method == 'GET':
        # 查询数据库该新闻
        news = None
        categories = []
        try:
            news = News.query.get(news_id)
            categories = Category.query.filter(Category.id != 1).all()
        except Exception as e:
            current_app.logger.error(e)
            abort(404)
        if not news:
            return redirect(url_for('admin.news_edit'))

        data = {
            'news': news.to_dict(),
            'categories': categories
        }
        return render_template('admin/news_edit_detail.html', **data)
    if request.method == 'POST':
        # 1.接收参数
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")
        # 2.校验参数
        if not all([title, digest, content, category_id]):
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数不全')
        # 根据id查询新闻是否存在
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.DBERR, errmag='数据查询失败')
        if not news:
            return jsonify(errno=response_code.RET.DATAERR, errmag='无此新闻')
        # 修改数据，进行提交
        if index_image:
            try:
                index_image_file = index_image.read()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=response_code.RET.PARAMERR, errmag='文件读取失败')
            try:
                key = upload_file(index_image_file)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=response_code.RET.THIRDERR, errmag='七牛云存储错误')
            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id
        news.status = 1
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DBERR, errmag='操作修改失败')
        return jsonify(errno=response_code.RET.OK, errmag='修改成功')

# 新闻编辑版式
@admin_blue.route('/news_edit')
def news_edit():
    # 1.获取参数
    page = request.args.get('p', '1')
    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = '1'

    news_list = []
    total_page = '1'
    current_page = '1'
    # 3.查询数据库
    try:
        keyword = request.args.get('keyword')
        if keyword:
            paginate = News.query.filter(News.status == 0, News.title.contains(keyword)).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:
            paginate = News.query.filter(News.status == 0).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page

    except Exception as e:
        current_app.logger.error(e)
    news_list_dict = []
    for news in news_list:
        news_list_dict.append(news.to_dict())

    data = {
        'news_list': news_list_dict,
        'total_page': total_page,
        'current_page': current_page
    }
    return render_template('admin/news_edit.html', **data)


# 新闻审核详情页
@admin_blue.route('/news_review_detail/<int:news_id>', methods=['GET', 'POST'])
def news_review_detail(news_id):

    if request.method == 'GET':
        # 查询详情新闻，根据id
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            return redirect(url_for('admin.news_review'))
        data = {
            'news': news.to_dict()
        }
        return render_template('admin/news_review_detail.html', **data)
    if request.method == 'POST':
        # 1.获取参数
        action = request.json.get('action')
        # 2.校验参数
        if not action:
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数不全')
        if action not in('accept', 'reject'):
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数错误')
        # 3.查询数据库
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.DBERR, errmag='数据库查询失败')
        if not news:
            return jsonify(errno=response_code.RET.DATAERR, errmag='无此新闻')
        if action == 'reject':
            reason = request.json.get('reason')
            if not reason:
                return jsonify(errno=response_code.RET.PARAMERR, errmag='请输入拒绝理由')
            news.reason = reason
            news.status = -1
        else:
            news.status = 0
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DBERR, errmag='数据库修改失败')
        # 响应结果
        return jsonify(errno=response_code.RET.OK, errmag='操作成功')


# 新闻审核列表
@admin_blue.route('/news_review')
def news_review():

    # 接收参数
    page = request.args.get('p', '1')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = '1'
    # 分页查询
    news_list = []
    total_page = 1
    current_page = 1

    try:
        keyword = request.args.get('keyword')
        if keyword:
            paginate = News.query.filter(News.status != 0, News.title.contains(keyword)).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:
            paginate = News.query.filter(News.status != 0).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    news_list_dict = []
    for news in news_list:
        news_list_dict.append(news.to_review_dict())
    data = {
        'news_list': news_list_dict,
        'total_page': total_page,
        'current_page': current_page
    }
    return render_template('admin/news_review.html', **data)


# 用户列表
@admin_blue.route('/user_list')
def user_list():
    # 1.获取参数
    page = request.args.get('p', "1")
    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = "1"
    # 3.查询数据库
    total_page = 1
    current_page = 1
    user_items = []
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        user_items = paginate.items
        total_page = paginate.pages
        current_page = paginate.page

    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    user_list_dict = []
    for user in user_items:
        user_list_dict.append(user.to_admin_dict())
    data = {
        'user_list': user_list_dict,
        'total_page': total_page,
        'current_page': current_page

    }
    return render_template('admin/user_list.html', **data)


# 用户统计
@admin_blue.route('/user_count')
def user_count():

    # 渲染界面
    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
    # 月新增数
    month_count = 0
    # 计算每月开始时间 比如：2018-06-01 00：00：00
    t = time.localtime()
    # 生成当前月份开始时间字符串
    month_begin = '%d-%02d-01' % (t.tm_year, t.tm_mon)
    # 生成当前月份开始时间对象
    month_begin_date = datetime.datetime.strptime(month_begin, '%Y-%m-%d')
    try:
        month_count = User.query.filter(User.is_admin == False, User.create_time > month_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 日新增数
    day_count = 0

    # 生成当天开始时间字符串
    day_begin = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    # 生成当前开始时间对象
    day_begin_date = datetime.datetime.strptime(day_begin, '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
    active_date = []
    active_count = []

    # 查询今天开始的时间
    today_begin = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    today_begin_date = datetime.datetime.strptime(today_begin, '%Y-%m-%d')

    for i in range(30):
        # 计算一天开始
        begin_date = today_begin_date-datetime.timedelta(days=i)
        # 计算一天结束
        end_date = today_begin_date-datetime.timedelta(days=(i-1))

        begin_date_str = datetime.datetime.strftime(begin_date, '%Y-%m-%d')
        # 将开始时间添加到列表中
        active_date.append(begin_date_str)
        # 查询数据库，计算数量
        count = 0
        try:
            count = User.query.filter(User.is_admin==False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)
    active_date.reverse()
    active_count.reverse()
    data = {
        'active_date': active_date,
        'active_count': active_count,
        'total_count': total_count,
        'month_count': month_count,
        'day_count': day_count
    }
    return render_template('admin/user_count.html', **data)


@admin_blue.route('/')
@user_login_data
def index():
    user = g.user
    if not user:
        return redirect(url_for('admin.admin_login'))
    data = {
        'user': user.to_dict()
    }
    return render_template('admin/index.html', **data)


@admin_blue.route('/login', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'GET':
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html')
    if request.method == 'POST':
        # 1.接收参数
        username = request.form.get('username')
        password = request.form.get('password')
        # 2.校验参数
        if not all([username, password]):
            return render_template('admin/login.html', errmsg='参数不足')
        # 3.查询数据库
        try:
            user = User.query.filter(User.nick_name == username).first()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/login.html', errmsg='用户查询失败')
        if not user:
            return render_template('admin/login.html', errmsg='无此用户')
        if not user.check_password(password):
            return render_template('admin/login.html', errmsg='用户名或密码错误')
        # 3.1 写入session
        session['user_id'] = user.id
        session['mobile'] = user.mobile
        session['nick_name'] = user.nick_name
        session['is_admin'] = user.is_admin
        # 4.响应结果
        return redirect(url_for('admin.index'))
